<template>
  <van-dialog 
    :show="itemsVisible" 
    title="" width="100%" 
    show-cancel-button
    @cancel="cancelSubmit"
    @confirm="doSubmit('objForm')"
  >
    <div class="approve-form">
      <van-form ref="approveForm">
        <van-field
          v-model="approveIdName"
          label="审批模版"
          disabled
          placeholder="请选择"
          input-align="right"
          right-icon="arrow"
          @click="showPicker1 = true"
        />
        <van-popup v-model:show="showPicker1" round position="bottom">
          <van-picker
            :columns="approveList"
            :columns-field-names="{text: 'approveName', value: 'id'}"
            @cancel="showPicker1 = false"
            @confirm="onConfirmPicker1"
          />
        </van-popup>
        <div class="approve-head">
          <h4>审批流</h4>
          <van-button type="success" @click="addApproveNode" size="small">新增审批节点</van-button>
        </div>
        <van-steps direction="vertical" :active="0">
          <van-step
            v-for="(node, index) in approveNodeList"
            :key="index"
            center
          >
            <div class="timeline-item">
              <!-- <el-form-item label="审批节点名称">
                <el-input v-model="node.approveNodeName" placeholder="请输入节点名称" :disabled="node.approveNodeSource === '1'" />
              </el-form-item> -->
              <van-field
                v-model="node.approveNodeName"
                label="审批节点名称"
                :disabled="node.approveNodeSource === '1'"
                placeholder="请输入节点名称"
                input-align="right"
              />
              <van-field name="radio" label="是否会签节点">
                <template #input>
                  <van-radio-group v-model="node.isCountersign" direction="horizontal" :disabled="node.approveNodeSource === '1'">
                    <van-radio v-for="(item,index) in getEnumList('CommonYesNo')" :name="item.key" :key="index">{{item.value}}</van-radio>
                  </van-radio-group>
                </template>
              </van-field>
              <van-field name="radio" label="节点类型" label-width="80" v-if="node.approveNodeSource === '1'">
                <template #input>
                  <van-radio-group v-model="node.approveNodeType" direction="horizontal" :disabled="node.approveNodeSource === '1'">
                    <van-radio  v-for="(item,index) in getEnumList('ApproveNodeType')" :name="item.key" :key="index">{{item.value}}</van-radio>
                  </van-radio-group>
                </template>
              </van-field>
              <selectOrganization label="审批节点组织架构" v-model="node.approveNodeOrgId" keyName="id" keyShow="organizationName" placeholder="部门" title="部门查询" :disabled="node.approveNodeSource === '1'" v-if="node.approveNodeSource === '1'" />
              <!-- <van-field name="aaa" label="审批节点组织架构" label-width="130" v-if="node.approveNodeSource === '1'">
                <template #input>
                  
                  <Organization v-model="node.approveNodeOrgId" keyName="id" keyShow="organizationName" placeholder="部门" title="部门查询" :disabled="node.approveNodeSource === '1'" />
                </template>
              </van-field> -->
              <!-- <van-field name="aaa" label="审批节点用户" v-if="node.approveNodeSource === '2'">
                <template #input>
                  <Organization v-model="node.approveNodeOrgId" keyName="id" keyShow="organizationName" placeholder="部门" title="部门查询" :disabled="node.approveNodeSource === '1'" />
                </template>
              </van-field> -->
              <selectUser label="审批节点用户" v-model="node.approveNodeUserId" keyName="id" keyShow="name" placeholder="用户" title="用户查询" :disabled="node.approveNodeSource === '1'" v-if="node.approveNodeSource === '2'" />
              <selectRole label="审批节点角色"  v-model="node.approveNodeRoleId" keyName="id" keyShow="roleName" placeholder="角色" title="角色查询" :disabled="node.approveNodeSource === '1'" v-if="node.approveNodeSource === '3'" />
              <!-- <van-field name="aaa" label="审批节点角色" v-if="node.approveNodeSource === '2'">
                <template #input>
                  <selectUser v-model="node.approveNodeUserId" keyName="id" keyShow="name" placeholder="用户" title="用户查询" :disabled="node.approveNodeSource === '1'" />
                </template>
              </van-field> -->
              <van-button type="danger" size="small" @click="delApproveNode(node.approveNodeNo)" :disabled="node.approveNodeSource === '1'" v-if="node.approveNodeSource === '2'">删除该节点</van-button>
            </div>
          </van-step>
        </van-steps>
      </van-form>
    </div>
</van-dialog>
</template>         

<script setup>
import {ref, watch} from "vue";
import {doGet} from "@/config/http";
import {getEnumList, getListPageSize, isNullOrUndefinedOrEmpty, svc} from "@/config/common";
import Organization from "@/views/components/base/selectOrganization.vue";
// import User from "@/views/components/base/selectUser.vue";
import Role from "@/views/components/base/selectRole.vue";
import selectUser from '@/h5/components/selectField/selectUser.vue'
import selectOrganization from '@/h5/components/selectField/selectOrganization.vue'
import selectRole from '@/h5/components/selectField/selectRole.vue'
import initListStore from '@/store/modules/initList'

const objForm = ref(null)
const obj = ref({
  approveId: null,
})

const itemsVisible = ref(false)
const business = ref(null)
const businessId = ref(null)

const props = defineProps({
  itemsVisible: {
    type: Boolean,
    default: false,
  },
  business: {
    type: String,
    default: null,
  },
  businessId: {
    type: String,
    default: null,
  },
})


let showPicker1 = ref(false)
let approveIdName = ref('')

const emit = defineEmits();

const governmentList = initListStore().governmentList
const organizationList = initListStore().organizationList
const userList = initListStore().userList
const roleList = initListStore().roleList

const approveList = ref([])
const approveNodeList = ref([])
const emptyApproveNode = {
  approveNodeSource: '2',
  approveNodeName: '审批节点1',
  approveNodeType: '2',
  approveNodeOrgId: null,
  approveNodeRoleId: null,
  approveNodeUserId: null,
  approveNodeNo: 1,
  isCountersign: '0', // 是否会签节点
}

// const initList = async () => {
//   if (!itemsVisible.value) {
//     return
//   }
//   let p1 = doGet(svc, '/government/page', {pageSize: getListPageSize()}, false)
//   let p2 = doGet(svc, '/organization/page', {pageSize: getListPageSize()}, false)
//   let p3 = doGet(svc, '/user/page', {pageSize: getListPageSize()}, false)
//   let p4 = doGet(svc, '/role/page', {pageSize: getListPageSize()}, false)
//   let resArray = await Promise.all([p1, p2, p3, p4])
//   governmentList.value = resArray[0]['records']
//   organizationList.value = resArray[1]['records']
//   userList.value = resArray[2]['records']
//   roleList.value = resArray[3]['records']
// }

const onConfirmPicker1 = async (data) => {
  console.log('data',data)
  obj.value.approveId = data.selectedOptions[0].id
  approveIdName.value = data.selectedOptions[0].approveName
  await changeApprove()
  showPicker1.value = false
}

watch(() => [props.itemsVisible, props.business, props.businessId], async vals => {
  console.log('props.itemsVisible',props.itemsVisible)
  itemsVisible.value = vals[0]
  business.value = vals[1]
  businessId.value = vals[2]
  if (isNullOrUndefinedOrEmpty(business) || isNullOrUndefinedOrEmpty(businessId)) {
    return
  }
  if (itemsVisible.value) {
    console.log('打开审批')
    // await initList()
    doGet(svc, '/customApprove/queryApproveByBusiness', {business: business.value, businessId: businessId.value}, false).then(res => {
      approveList.value = res
      if (approveList.value.length > 0) {
        obj.value.approveId = approveList.value[0].id
        approveIdName.value = approveList.value[0].approveName
        changeApprove()
      }
    })
  }
})

async function changeApprove() {
  approveNodeList.value = await doGet(svc, '/approve-node/listByField', {field:'approveId', values:obj.value.approveId}, false)
  approveNodeList.value.map(item => item.approveNodeSource = '1')

  approveNodeList.value.map(item => {
    const organizationIds = item?.approveNodeOrgId?.split(',')
    item.approveNodeOrgNames = organizationList.value.filter(item => organizationIds?.includes(item.id)).map(m => m.name).join(',')
    const roleIds = item?.approveNodeRoleId?.split(',')
    item.approveNodeRoleNames = roleList.value.filter(item => roleIds?.includes(item.id)).map(m => m.name).join(',')
    const userIds = item?.approveNodeUserId?.split(',')
    item.approveNodeUserNames = userList.value.filter(item => userIds?.includes(item.id)).map(m => m.name).join(',')
  })

  console.log('approveNodeList.value',approveNodeList.value)
}

function addApproveNode() {
  console.log('approveNodeList.value',approveNodeList.value)
  if (approveNodeList.value.length >= 5) {
    return
  }
  let o = Object.assign({}, emptyApproveNode)
  let nodeIdx = approveNodeList.value.length + 1
  o.approveNodeNo = nodeIdx
  o.approveNodeName = '新增审批节点' + nodeIdx
  approveNodeList.value.unshift(o)
  let no = 1;
  approveNodeList.value.map(item => item.approveNodeNo = no++)
  
}

function delApproveNode(nodeIdx) {
  let idx = approveNodeList.value.findIndex(item => item['approveNodeNo'] === nodeIdx)
  approveNodeList.value.splice(idx, 1)
  let no = 1;
  approveNodeList.value.map(item => item.approveNodeNo = no++)
}

function cancelSubmit() {
  emit('cancel')
}
function doSubmit(objForm) {
  console.debug('objForm', objForm)
  obj.value.approveNodes = approveNodeList.value
  console.debug('obj', obj.value)
  emit('doSubmit', obj.value)
}
</script>
<style scoped>
.approve-form {
  max-height: 80vh;
  overflow-y: auto;
}
.timeline {
  width: 100%;
  margin-right: 50px;
}
.approve-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: .625rem .9375rem;
}
.timeline-item {
  /* margin: 10px 0; */
  /* border:1px solid #ccc; */
  /* border-radius: 5px; */
  /* padding: 10px 25px; */
}
</style>
